package com.example.myapplication;

import android.app.Instrumentation;
import android.app.UiAutomation;
import android.view.accessibility.AccessibilityNodeInfo;
import java.lang.reflect.Method;

public class UiAutomationDumper {
    public static String dumpUiHierarchy() {
        try {
            // 通过反射获取当前进程的 Instrumentation
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
            Object activityThread = currentActivityThreadMethod.invoke(null);
            Method getInstrumentationMethod = activityThreadClass.getDeclaredMethod("getInstrumentation");
            getInstrumentationMethod.setAccessible(true);
            Instrumentation instrumentation = (Instrumentation) getInstrumentationMethod.invoke(activityThread);

            // 获取 UiAutomation
            UiAutomation uiAutomation = instrumentation.getUiAutomation();
            AccessibilityNodeInfo rootNode = uiAutomation.getRootInActiveWindow();

            if (rootNode != null) {
                StringBuilder uiDump = new StringBuilder();
                dumpNodeInfo(rootNode, uiDump, 0);
                return uiDump.toString();
            } else {
                return "获取 RootInActiveWindow 失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "发生异常: " + e.getMessage();
        }
    }

    private static void dumpNodeInfo(AccessibilityNodeInfo node, StringBuilder builder, int depth) {
        if (node == null) return;

        // 缩进表示层级结构
        for (int i = 0; i < depth; i++) {
            builder.append("  ");
        }

        // 记录节点信息
        builder.append("Class: ").append(node.getClassName())
                .append(", Text: ").append(node.getText())
                .append(", ContentDesc: ").append(node.getContentDescription())
                .append("\n");

        // 遍历子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            dumpNodeInfo(node.getChild(i), builder, depth + 1);
        }
    }
}
